<template>
  <div class="clue-detail-container">
    <div class="page-header">
      <div class="left">
        <h2>线索详情</h2>
      </div>
      <div class="right">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="线索姓名" :span="1">
          {{ clue?.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="公司名称" :span="1">
          {{ clue?.company || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="职位" :span="1">
          {{ clue?.position || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话" :span="1">
          {{ clue?.phone || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱地址" :span="1">
          {{ clue?.email || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="线索来源" :span="1">
          <el-tag :type="getSourceType(clue?.source)" size="small" effect="light">
            {{ getSourceName(clue?.source) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级" :span="1">
          <el-tag :type="getPriorityType(clue?.priority)" size="small" effect="light">
            {{ getPriorityName(clue?.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="线索状态" :span="1">
          <el-tag :type="getStatusType(clue?.status)" size="small" effect="light">
            {{ getStatusName(clue?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="负责人" :span="1">
          {{ clue?.ownerName || '未分配' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="1">
          {{ formatTime(clue?.createAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="1">
          {{ formatTime(clue?.updateAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="下次跟进时间" :span="1">
          {{ formatTime(clue?.nextFollowUpTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="行为描述" :span="2">
          <div class="content-text">{{ clue?.behavior || '-' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="2">
          <div class="content-text">{{ clue?.remark || '-' }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 跟进记录 -->
    <el-card class="followup-card">
      <template #header>
        <div class="card-header">
          <span>跟进记录</span>
          <el-button type="primary" @click="showFollowUpDialog = true">
            <el-icon><Plus /></el-icon>
            添加跟进
          </el-button>
        </div>
      </template>

      <div v-if="followUps.length === 0" class="empty-state">
        <el-empty description="暂无跟进记录" />
      </div>

      <el-timeline v-else>
        <el-timeline-item
          v-for="item in followUps"
          :key="item.id"
          :timestamp="formatTime(item.followUpTime)"
          placement="top"
        >
          <el-card class="timeline-card">
            <div class="followup-header">
              <div class="followup-method">
                <el-tag size="small" effect="light">{{ item.method }}</el-tag>
                <span class="followup-user">{{ item.userName || '未知用户' }}</span>
              </div>
              <el-button type="danger" link size="small" @click="handleDeleteFollowUp(item)">
                删除
              </el-button>
            </div>
            <div class="followup-content">{{ item.content }}</div>
            <div v-if="item.nextPlanTime" class="next-plan">
              <el-icon><Clock /></el-icon>
              下次跟进：{{ formatTime(item.nextPlanTime) }}
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 添加跟进对话框 -->
    <el-dialog
      v-model="showFollowUpDialog"
      title="添加跟进记录"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="followUpForm"
        :rules="followUpRules"
        ref="followUpFormRef"
        label-width="120px"
      >
        <el-form-item label="跟进方式" prop="method">
          <el-select v-model="followUpForm.method" placeholder="请选择跟进方式" style="width: 100%">
            <el-option label="电话" value="PHONE" />
            <el-option label="邮件" value="EMAIL" />
            <el-option label="面对面" value="FACE_TO_FACE" />
            <el-option label="微信" value="WECHAT" />
            <el-option label="QQ" value="QQ" />
            <el-option label="短信" value="SMS" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="followUpForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容"
          />
        </el-form-item>
        <el-form-item label="跟进时间" prop="followUpTime">
          <el-date-picker
            v-model="followUpForm.followUpTime"
            type="datetime"
            placeholder="选择跟进时间"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="下次计划时间">
          <el-date-picker
            v-model="followUpForm.nextPlanTime"
            type="datetime"
            placeholder="选择下次跟进时间"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="设置提醒">
          <el-switch v-model="followUpForm.remind" />
        </el-form-item>
        <el-form-item v-if="followUpForm.remind" label="提醒时间">
          <el-date-picker
            v-model="followUpForm.remindTime"
            type="datetime"
            placeholder="选择提醒时间"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFollowUpDialog = false">取消</el-button>
          <el-button type="primary" @click="submitFollowUp" :loading="submitting"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Clock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getClue, getClueFollowUps, addClueFollowUp, deleteClueFollowUp } from '@/api/clue'
import type { Clue, ClueFollowUp } from '@/types/clue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const clue = ref<Clue | null>(null)
const followUps = ref<ClueFollowUp[]>([])
const showFollowUpDialog = ref(false)
const followUpFormRef = ref<FormInstance>()

const followUpForm = reactive({
  clueId: Number(route.params.id),
  method: '',
  content: '',
  followUpTime: null as number | null,
  nextPlanTime: null as number | null,
  remind: false,
  remindType: '',
  remindTime: null as number | null,
})

const followUpRules = reactive<FormRules>({
  method: [{ required: true, message: '请选择跟进方式', trigger: 'change' }],
  content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
  followUpTime: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
})

const loadClue = async () => {
  loading.value = true
  try {
    const res = await getClue(Number(route.params.id))
    clue.value = res.data
  } catch (error) {
    console.error('加载线索详情失败:', error)
    ElMessage.error('加载线索详情失败')
  } finally {
    loading.value = false
  }
}

const loadFollowUps = async () => {
  try {
    const res = await getClueFollowUps(Number(route.params.id))
    followUps.value = res.data
  } catch (error) {
    console.error('加载跟进记录失败:', error)
    ElMessage.error('加载跟进记录失败')
  }
}

const submitFollowUp = async () => {
  if (!followUpFormRef.value) return

  await followUpFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await addClueFollowUp(Number(route.params.id), followUpForm)
        ElMessage.success('添加成功')
        await recordOperation('ADD_FOLLOWUP', `添加线索跟进记录`)
        showFollowUpDialog.value = false
        // 重置表单
        Object.assign(followUpForm, {
          method: '',
          content: '',
          followUpTime: null,
          nextPlanTime: null,
          remind: false,
          remindType: '',
          remindTime: null,
        })
        loadFollowUps()
      } catch (error) {
        console.error('添加跟进记录失败:', error)
        ElMessage.error('添加跟进记录失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const handleDeleteFollowUp = async (item: ClueFollowUp) => {
  try {
    await ElMessageBox.confirm('确认删除该跟进记录吗？', '提示', {
      type: 'warning',
    })
    await deleteClueFollowUp(item.id!)
    ElMessage.success('删除成功')
    await recordOperation('DELETE_FOLLOWUP', `删除线索跟进记录`)
    loadFollowUps()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除跟进记录失败:', error)
      ElMessage.error('删除跟进记录失败')
    }
  }
}

// 获取来源类型样式
const getSourceType = (source?: string) => {
  if (!source) return 'info'
  const types: Record<string, string> = {
    WEBSITE: 'primary',
    PHONE: 'success',
    EMAIL: 'info',
    EXHIBITION: 'warning',
    REFERRAL: 'danger',
    ADVERTISEMENT: 'primary',
    OTHER: 'info',
  }
  return types[source] || 'info'
}

// 获取来源名称
const getSourceName = (source?: string) => {
  if (!source) return '-'
  const names: Record<string, string> = {
    WEBSITE: '官网',
    PHONE: '电话',
    EMAIL: '邮件',
    EXHIBITION: '展会',
    REFERRAL: '推荐',
    ADVERTISEMENT: '广告',
    OTHER: '其他',
  }
  return names[source] || source
}

// 获取优先级类型样式
const getPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const types: Record<string, string> = {
    HIGH: 'danger',
    MEDIUM: 'warning',
    LOW: 'success',
  }
  return types[priority] || 'info'
}

// 获取优先级名称
const getPriorityName = (priority?: string) => {
  if (!priority) return '-'
  const names: Record<string, string> = {
    HIGH: '高',
    MEDIUM: '中',
    LOW: '低',
  }
  return names[priority] || priority
}

// 获取状态类型样式
const getStatusType = (status?: string) => {
  if (!status) return 'info'
  const types: Record<string, string> = {
    NEW: 'info',
    ASSIGNED: 'warning',
    CLAIMED: 'primary',
    CONVERTED: 'success',
    RECYCLED: 'danger',
    AUTO_RECYCLED: 'danger',
  }
  return types[status] || 'info'
}

// 获取状态名称
const getStatusName = (status?: string) => {
  if (!status) return '-'
  const names: Record<string, string> = {
    NEW: '新建',
    ASSIGNED: '已分配',
    CLAIMED: '已领取',
    CONVERTED: '已转化',
    RECYCLED: '已回收',
    AUTO_RECYCLED: '自动回收',
  }
  return names[status] || status
}

// 格式化时间
const formatTime = (time?: string | number) => {
  if (!time) return '-'
  const date = new Date(typeof time === 'string' ? time : time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 记录操作日志
const recordOperation = async (action: string, description: string) => {
  try {
    await axios.post('/api/logs', {
      action,
      description,
    })
  } catch (error) {
    console.error('记录操作日志失败:', error)
  }
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问线索详情页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

const goBack = () => {
  router.push('/clues')
}

onMounted(() => {
  loadClue()
  loadFollowUps()
  recordPageAccess()
})
</script>

<style scoped>
.clue-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 56px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header .left h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #1f2f3d;
}

.detail-card {
  margin-bottom: 20px;
}

.followup-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-text {
  white-space: pre-wrap;
  word-break: break-all;
  max-width: 400px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.timeline-card {
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.followup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.followup-method {
  display: flex;
  align-items: center;
  gap: 8px;
}

.followup-user {
  color: #606266;
  font-size: 14px;
}

.followup-content {
  margin-bottom: 8px;
  color: #303133;
  line-height: 1.6;
}

.next-plan {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-descriptions :deep(.el-descriptions__label) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.el-descriptions :deep(.el-descriptions__content) {
  background-color: #fff;
  color: #303133;
}
</style>
